package com.scau.yangsuiyu.estore.dababases.dao;

import com.scau.yangsuiyu.estore.dababases.entity.Seller;
import com.scau.yangsuiyu.estore.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * @author suiyu_yang
 * @description seller的dao类
 * @date 2019-05-23 14:31
 * @email suiyu_yang@163.com
 */
public class SellerDao{

    public void insert(Seller seller) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.save(seller);

        transaction.commit();
        HibernateUtil.closeSession();
    }

    public void delete(Seller seller) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.delete(seller);

        transaction.commit();
        HibernateUtil.closeSession();

    }

    public void update(Seller seller) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.update(seller);

        //当事务提交时，hibernate会自动按照一定的策略将session中的持久化对象，同步到数据库中，从而自动使数据库的状态和session中的对象状态完全一致。
        // 如果要在事务提交前同步，则可以使用session的flush方法。
        session.flush();

        transaction.commit();
        HibernateUtil.closeSession();
    }


    public Seller getSellerByPhone(String phone) {
        Session session = HibernateUtil.currentSession();

        String sql = "from Seller seller where seller.phone = '" + phone + "' ";

        Seller seller = (Seller) session.createQuery(sql).uniqueResult();
        HibernateUtil.closeSession();
        return seller;
    }

    public Seller getSellerByEmail(String email) {
        Session session = HibernateUtil.currentSession();

        String sql = "from Seller seller where seller.email = '" + email + "' ";

        Seller seller = (Seller) session.createQuery(sql).uniqueResult();

        HibernateUtil.closeSession();
        return seller;
    }

    public Seller getSellerByUsername(String username) {
        Session session = HibernateUtil.currentSession();

        String sql = "from Seller seller where seller.username = '" + username + "' ";

        Seller seller = (Seller) session.createQuery(sql).uniqueResult();

        HibernateUtil.closeSession();
        return seller;
    }

}
